package cn.tedu.egmvc5.controller;

import cn.tedu.egmvc5.base.response.JsonResult;
import cn.tedu.egmvc5.base.response.StatusCode;
import cn.tedu.egmvc5.mapper.UserMapper;
import cn.tedu.egmvc5.pojo.dto.ArticleParam;
import cn.tedu.egmvc5.pojo.dto.UserLoginParam;
import cn.tedu.egmvc5.pojo.entity.Article;
import cn.tedu.egmvc5.pojo.vo.ArticleVO;
import cn.tedu.egmvc5.pojo.vo.UserQuery;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;
@Validated
@RestController
@RequestMapping("/v1/user/")
@Slf4j
@Api(tags = "用户管理")
public class UserController {
    @Autowired
    private UserMapper userMapper;
    @PostMapping("login")
    @ApiOperation("登录功能")
    @ApiOperationSupport(order = 10)
    public JsonResult login(@RequestBody UserLoginParam userLoginParam, @ApiIgnore HttpSession session){
        log.debug("userLoginParam:"+userLoginParam);
        String username = userLoginParam.getUsername();
        String password = userLoginParam.getPassword();
        UserQuery userQuery= (UserQuery)userMapper.selectByusernameAndPassword(username,password);
        if (userQuery==null){
            return new JsonResult(StatusCode.USER_PASSWORD_ERROR);
        }
        session.setAttribute("user",userQuery);
        return JsonResult.ok(userQuery);
    }
    @PostMapping("article")
    @ApiOperation("发表文章")
    @ApiOperationSupport(order = 20)
    public JsonResult article(@RequestBody  @Validated ArticleParam articleParam, @ApiIgnore HttpSession session){
        UserQuery  userQuery = (UserQuery)session.getAttribute("user");
        Article article = new Article();
        BeanUtils.copyProperties(articleParam,article);
        article.setUserId(userQuery.getId());
        userMapper.insetArticle(article);
        return JsonResult.ok(article);
    }
    @GetMapping("selectByArticleId")
    @ApiOperation("查看指定文章")
    @ApiOperationSupport(order = 30)
    public JsonResult selectArticle(@Range(min = 1,max = 100,message = "文章ID要求在1-100之") @RequestParam Integer id){
        ArticleVO  articleVO = userMapper.electByArticleId(id);
        return JsonResult.ok(articleVO);
    }
}

















